# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from signal import SIGTERM


_DEFAULT_PORT = 33690

_conf = """[general]
password-db = passwd
"""

_passwd = """[users]
unittest=rayjandom
basil=rayjandom
jrandom=rayjandom
jconstant=rayjandom
"""


def GetPort():
  return int(os.getenv('SVN_PORT', _DEFAULT_PORT))

class Svnserve(object):
  def __init__(self, home, svnserve=None):
    self.home = home
    if svnserve is None:
      self.svnserve = 'svnserve'
    else:
      self.svnserve = svnserve
    self.port = GetPort()

  config_file = property(lambda self: self.home + '/svnserve.conf')
  passwd = property(lambda self: self.home + '/passwd')

  def start(self):
    fp = open(self.config_file, 'w')
    fp.write(_conf)
    fp.close()
    fp = open(self.passwd, 'w')
    fp.write(_passwd)
    fp.close()

    self.pid = os.fork()
    if self.pid == 0:
      os.setpgrp()
      os.execlp(self.svnserve, self.svnserve, '-d', '--foreground',
                '--listen-host', '127.0.0.1', '--listen-port', str(self.port),
                '-r', self.home, '--config-file', self.config_file)

  def stop(self):
    os.kill(self.pid, SIGTERM)
